<?php
namespace app\common\model\cms;

use app\common\model\BaseModel;
use org\util\TreeUtil;
use think\facade\Cache;

class ClassModel extends BaseModel
{
    protected $name = 'cms_class';
    protected $pk='id';

    protected $autoWriteTimestamp = true;
    //设置类型转换
    protected $type = [];
    //设置json类型字段
    protected $json = [];

    /**
     * 内容选择列表
     * @param $moudleId
     * @return array
     * @throws \Exception
     */
    public function formatContentSelect($moudleId){
        $cat = $this->getList();
        $category=[];
        //栏目必须处理到各自模型
        foreach ($cat as $v) {
            $v['disabled'] = '';
            if($v['moudle_id']!=$moudleId){
                continue;
//                $v['disabled'] = 'disabled'; //排除非本模型栏目
//                $v['_name'] = $v['_name'].'(非本模型)'; //排除外部链接
            }
            if ($v['class_type'] == 1){
                continue;
//                $v['disabled'] = 'disabled'; //排除外部链接
//                $v['_name'] = $v['_name'].'(外)'; //排除外部链接
            }
            if($v['is_content_add']==0) $v['disabled'] = 'disabled';  //禁用不允许添加内容的栏目
            $category[]=$v;
        }
        return $category;
    }
    /**
     * 获取选择栏目列表
     */
    public function formatSelectList($cat,$channelId=0){
        $category=[];
        //栏目必须处理到各自模型
        foreach ($cat as $v) {
            //排除外部链接
            if ($v['class_type'] == 1) continue;
            //排除不允许添加栏目
            if ($v['is_class_add'] == 0) continue;
            $v['disabled'] = '';
            //当前栏目默认选中
            if($channelId>0){
                $info = $cat[$channelId];
                $dataView = explode(',',$info['data_view']);
                array_pop($dataView); //去除本身ID
                if(in_array($v['id'],$dataView)){
                    $v['disabled'] = ' disabled';
                }
            }
            $category[]=$v;
        }
        return $category;
    }

    /**
     * 获取指定权限列表
     * @return mixed
     * @throws \Exception
     */
    public function getList(){
        if(!Cache::has('cms_class')){
            $this->updateCache();
        }
        $list = Cache::get('cms_class');
        return $list;
    }
    /**
     * 获取树型列表
     */
    public function getTreeList(){
        $list = $this->getList();
        $list = array_values($list);
        $treeList = TreeUtil::channelLevel($list,0);
        return $treeList;
    }

    /**
     * 获取信息
     * @param $map
     * @return array|\PDOStatement|string|\think\Model|void|null
     */
    public function getInfo($map){
        $dbInfo = $this->where($map)->find();
        $list = $this->getList();
        $info = $list[$dbInfo['id']];
        $info['class_content'] = html_out($dbInfo['class_content']); //补充内容字段
        return $info;
    }

    /**
     * 添加权限
     * @param $data
     */
    public function addData($data){
        try{
            $info = self::create($data);
            $this->updateCache();
        }catch (\Exception $e){
            exception($e->getMessage(),$e->getCode());
        }
        return $info;
    }

    /**
     * 编辑权限
     * @param $data
     */
    public function editData($data){
        try{
            $info = self::update($data);
            $this->updateCache();
        }catch (\Exception $e){
            exception($e->getMessage(),$e->getCode());
        }
        return $info;
    }

    /**
     * 读取扩展信息
     */
    public function formatExtend($extend){
        //$str = '{"extend_image1":"\/upload\/images\/20181206\/1dbf91f086858b0381160b2b31d28f9e.jpg","extend_image2":"","extend_image3":"","extend_images":"[{\"url\":\"\\\/upload\\\/images\\\/20181206\\\/9d3504311dafbe524620335653a34c10.jpg\",\"title\":\"\",\"remark\":\"\",\"href\":\"\"},{\"url\":\"\\\/upload\\\/images\\\/20181206\\\/a69dbe2af2a0e002dd95d18158c45168.jpg\",\"title\":\"\",\"remark\":\"\",\"href\":\"\"}]","extend_items":[],"extend_input1":"1","extend_input2":"2","extend_input3":"3","extend_textarea1":"4","extend_textarea2":"5","extend_textarea3":"6"}';
        $extendArr = json_decode($extend,true);
        $extendArr['extend_images'] = json_decode($extendArr['extend_images'],true);
        return $extendArr;
    }
    /**
     * 设置扩展信息
     */
    public function saveExtend($data){
        $extendImages = $this->formatMultiImageDesc($data['extend_images']); //json字符串
        $extendItems = empty($data['extend_items']) ? [] : $data['extend_items']; //数组
        $extend['extend_image1'] = $data['extend_image1'];
        $extend['extend_image2'] = $data['extend_image2'];
        $extend['extend_image3'] = $data['extend_image3'];
        $extend['extend_images'] = $extendImages; //还原数组
        $extend['extend_items'] = $extendItems; //项目列表
        $extend['extend_input1'] = $data['extend_input1'];
        $extend['extend_input2'] = $data['extend_input2'];
        $extend['extend_input3'] = $data['extend_input3'];
        $extend['extend_textarea1'] = $data['extend_textarea1'];
        $extend['extend_textarea2'] = $data['extend_textarea2'];
        $extend['extend_textarea3'] = $data['extend_textarea3'];
        $extendJson = json_encode($extend,true);
        $this->where('id',$data['id'])->setField('extend',$extendJson);
    }
    /**
     * 删除栏目
     * @param $id
     * @throws \Exception
     */
    public function delData($id) {
        $list = $this->getList();
        $channelInfo = $list[$id];
        if($channelInfo['has_child']==1) exception('存在下级栏目，不允许删除！');
        if(cms_model($channelInfo['moudle_id'])->where('class_id',$id)->find()){
            exception('该栏目下存在内容，不允许删除！');
        }
        $this->where('id',$id)->delete();
    }
    /**
     * 缓存指定模块数据
     * @param $moudleValue
     * @return bool
     * @throws \Exception
     */
    public function updateCache(){
        try{
            $list = $this->field('class_content',true)->order('show_order asc')->select();
            $list = $list->isEmpty()?[]:$list->toArray();
            $list = TreeUtil::tree($list, 'name');
            $cache=[];
            foreach($list as $k=>$v){
                $hasChild = 0; //默认无下级
                $v['next_level_ids']=[]; //下级分类id
                $child = TreeUtil::channelList($list,$v['id']);
                $dataView = array_column($child,'id');
                if(!empty($dataView)){
                    $hasChild = 1;
                    foreach($child as $kk=>$vv){
                        if($vv['pid']==$v['id']) $v['next_level_ids'][]=$vv['id'];
                    }
                }
                $dataView[]=$v['id'];
                $v['data_view'] = implode(',',$dataView); //所有下级ID，包括本身
                $v['has_child'] = $hasChild;
                $v['next_level_ids'] = implode(',',$v['next_level_ids']);
                //取所有上级
                $parents = array_reverse(TreeUtil::parentChannel($list, $v['id']));
                $v['location'] = $parents;
                $fullName = array_column($parents,'name');
                $path = array_column($parents,'id');
                $v['full_name'] = implode(',',$fullName);
                $v['path'] = implode(',',$path);
                $cache[$v['id']] = $v;
            }
            Cache::set('cms_class',$cache);
        }catch (\Exception $e){
            exception($e->getMessage());
        }
        return true;
    }
}